package org.groovymud.object.registry.cloneutils;

import java.util.List;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * hook into the xstream marshaller to return the mud instances of certain objects that might 
 * be persisted instead of marshalling and unmarshalling them 
 * @author corbym
 *
 */
public class CloneConverter implements Converter, ApplicationContextAware {


    private ApplicationContext applicationContext;

    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		// do not do anything
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        return applicationContext.getBeansOfType(context.getRequiredType(), false, true);
	}


	public boolean canConvert(Class type) {
		return applicationContext.getBeanNamesForType(type).length == 1; // single instances only
	}

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
